// example 9_7
#include "QMoviePlayer.hpp"
#include "ui_QMoviePlayer.h"
#include <QTimer>
#include <QPainter>
QMoviePlayer::QMoviePlayer(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QMoviePlayer)
{
    ui->setupUi(this);
}

QMoviePlayer::~QMoviePlayer()
{
    delete ui;
}

bool QMoviePlayer::open(string file)
{
    if (!m_cap.open(file)) return false;

    m_cap.read(m_cv_img);
    m_qt_img = QImage(QSize(m_cv_img.cols, m_cv_img.rows), QImage::Format_RGB888);
    ui->frame->setMinimumSize(m_qt_img.width(), m_qt_img.height());
    ui->frame->setMaximumSize(m_qt_img.width(), m_qt_img.height());

    _copyImage();
    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(nextFrame()));
    m_timer->start(1000. / m_cap.get(cv::CAP_PROP_FPS));
    return true;
}

void QMoviePlayer::paintEvent(QPaintEvent *q)
{
    QPainter painter(this);
    painter.drawImage(QPoint(ui->frame->x(), ui->frame->y()), m_qt_img);
}

void QMoviePlayer::_copyImage()
{
    cv::Mat cv_header_to_qt_image(cv::Size(m_qt_img.width(), m_qt_img.height()), CV_8UC3, m_qt_img.bits());
    cv::cvtColor(m_cv_img, cv_header_to_qt_image, cv::COLOR_BGR2RGB);
}

void QMoviePlayer::nextFrame()
{
    if (!m_cap.isOpened()) return;

    m_cap.read(m_cv_img);
    _copyImage();

    this->update();
}
